package org.wskyh.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class UDPServer {
    public static void main(String[] args) throws SocketException {
        DatagramSocket socket = new DatagramSocket(8899);       // 开启服务端
        ArrayList<InetSocketAddress> clients = new ArrayList<>();           // 用于存放客户端的集合
        // 接收消息线程
        new Thread(() -> {
            try {
                byte[] bytes;
                do {
                    bytes = new byte[1024];
                    DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
                    socket.receive(packet);
                    InetSocketAddress client = new InetSocketAddress(packet.getAddress(), packet.getPort());
                    if (!clients.contains(client)) {
                        clients.add(client);
                    }
                    System.out.println(packet.getAddress() + "：" + new String(packet.getData()));
                } while (!"exit".equals(new String(Arrays.copyOf(bytes, 4))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        // 发送消息线程
        new Thread(() -> {
            // 反复发送消息
            String request;
            Scanner scanner = new Scanner(System.in);

            String index = "1";
            do {
                request = scanner.next();

                // 如果有多个客户端，则让用户选择
                if (clients.size() != 1) {
                    System.out.println("请选择要发送的客户端：");
                    // 遍历所有客户端的IP地址
                    for (int i = 0; i < clients.size(); i++) {
                        System.out.println(i + 1 + ". " + clients.get(i));
                    }
                    System.out.println("*. 所有客户端");
                    index = scanner.next();
                }

                // 发送消息
                try {
                    if ("*".equals(index)) {
                        // 如果输入*，则发给所有人
                        for (InetSocketAddress client : clients) {
                            socket.send(new DatagramPacket(request.getBytes(), request.getBytes().length, client.getAddress(), client.getPort()));
                        }
                    } else {
                        // 否则发给特定的客户端
                        InetSocketAddress client = clients.get(Integer.parseInt(index) - 1);
                        socket.send(new DatagramPacket(request.getBytes(), request.getBytes().length, client.getAddress(), client.getPort()));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } while (!"exit".equals(request));
        }).start();
    }
}